from browser import document
from browser import html
from browser import ajax
from browser import alert
from browser import window
import json

saveGroupInfo = document["saveGroupInfo"]
inputGroupname = document["inputGroupname"]
inputHostsId = document["inputHostsId"]
inputGroupRemask = document["inputGroupRemask"]

def addUserDatas(req):
    data = json.loads(req.text)
    alert(data)
    window.location.href = "./index.html?page=groups"


def addGroup(ev):
    groupnameVal = inputGroupname.value
    groupRemask = inputGroupRemask.value
    groupHostsVal = ""

    for item in inputHostsId:
        if item.selected:
            if groupHostsVal == "":
                groupHostsVal = str(item.value)
                continue

            groupHostsVal = groupHostsVal + ":" + str(item.value)


    reqData = {}
    reqData["name"] = groupnameVal
    reqData["hostids"] = groupHostsVal
    reqData["remask"] = groupRemask


    request = ajax.Ajax()
    request.bind("complete", addUserDatas)
    request.open("POST", "/manageGroups", False)
    request.send(reqData)

    inputGroupname.value = ""
    inputGroupRemask.value = ""

def updateOptions(req):
    data = json.loads(req.text)
    if data["Code"] == 0:
        for item in  data["Data"]:
            option = html.OPTION(str(item["Id"]) + " "  +item["Addr"] + " "+ item["Remask"])
            option.value = item["Id"]

            inputHostsId <= option

request = ajax.Ajax()
request.bind("complete", updateOptions)
request.open("GET", "/showHosts", False)
request.send()

saveGroupInfo.bind("click",addGroup)